package com.gitee.qdbp.general.system.biz.tenant.service;

import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.able.jdbc.ordering.OrderPaging;
import com.gitee.qdbp.able.jdbc.paging.PageList;
import com.gitee.qdbp.able.result.ResultCode;
import com.gitee.qdbp.base.system.model.IAccount;
import com.gitee.qdbp.general.common.api.sequence.model.SimpleSequenceRule;
import com.gitee.qdbp.general.common.api.sequence.service.ISimpleSequenceGenerator;
import com.gitee.qdbp.general.common.enums.UsingState;
import com.gitee.qdbp.general.system.api.tenant.model.TenantCoreBean;
import com.gitee.qdbp.general.system.api.tenant.model.TenantCoreWhere;
import com.gitee.qdbp.general.system.api.tenant.service.ITenantCoreExecutor;
import com.gitee.qdbp.general.system.biz.tenant.basic.TenantCoreBasic;
import com.gitee.qdbp.general.system.enums.TenantType;
import com.gitee.qdbp.general.system.error.TenantErrorCode;
import com.gitee.qdbp.tools.utils.VerifyTools;

/**
 * 租户信息业务处理类
 *
 * @author zhh
 * @version 181029
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public class TenantCoreExecutor implements ITenantCoreExecutor {

    /** 日志对象 **/
    private static final Logger log = LoggerFactory.getLogger(TenantCoreExecutor.class);

    @Autowired
    private TenantCoreBasic tenantCoreBasic;
    @Autowired
    private ISimpleSequenceGenerator codeSequenceGenerator;

    @Override
    public String generateTenantCode() {
        int codeLength = 6;
        SimpleSequenceRule rule = new SimpleSequenceRule((int) Math.pow(10, codeLength - 1) * 5 + 1);
        rule.setName("TenantCode");
        return codeSequenceGenerator.use(rule).generate("TENANT_CODE");
    }

    @Override
    public String create(TenantCoreBean model, IAccount me) throws ServiceException {
        String msg = "Failed to create TenantCoreInfo. ";

        if (VerifyTools.isBlank(me)) {
            log.error(msg + "params is null: me");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (VerifyTools.isBlank(model)) {
            log.error(msg + "params is null: model");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        String tenantName = model.getTenantName();
        if (VerifyTools.isBlank(tenantName)) {
            log.error(msg + "params is null: TenantName");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (VerifyTools.isBlank(model.getTenantType())) {
            model.setTenantType(TenantType.TEAM);
        }

        // 校验名称唯一性
        checkTenantNameThrowOnAlreadyExists(tenantName, msg);

        if (VerifyTools.isBlank(model.getTenantCode())) { // 生成租户编号
            model.setTenantCode(generateTenantCode());
        }
        // 默认选项
        model.setId(null); // 主键由Basic生成, 不允许外部传入
        model.setUsingState(UsingState.ENABLED);
        model.setCreatorId(me.getId()); // 创建人ID
        model.setCreateTime(new Date()); // 创建时间

        // 向saas_tenant_core_info表插入记录
        tenantCoreBasic.create(model);

        return model.getTenantCode();
    }

    private void checkTenantNameThrowOnAlreadyExists(String tenantName, String msg) {

        TenantCoreWhere where = new TenantCoreWhere();
        where.setTenantName(tenantName);
        PageList<?> paged = tenantCoreBasic.list(where, OrderPaging.COUNT);
        if (paged.getTotal() > 0) {
            log.info(msg + "tenant name already exist: {}", tenantName);
            throw new ServiceException(TenantErrorCode.TENANT_NAME_ALREADY_OCCUPIED);
        }
    }
}
